<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');
App::uses('Sanitize', 'Utility');
App::uses('Xml', 'Utility');
/**
 * Articles Controller
 *
 * @property Article $Article
 */
class ArticlesController extends AppController {
	
	public $helpers = array('Cksource','FileUpload.FileUpload','Tree');
	public $components = array('FileUpload.FileUpload','RequestHandler','Search.Prg');
	
	public $presetVars = true; // using the model configuration
// 	public $presetVars = array(
// 			'content' => array('type' => 'like')
// 	);
	public function beforeFilter(){
		parent::beforeFilter();
// 		$this->FileUpload->uploadDir('files');
		$this->Auth->allow('display','feed','events','search');
	}
	

	public function beforeRender(){
		parent::beforeRender();
		switch($this->action){
			case 'display':
				$this->layout = 'default';
				break;
			case 'feed':
				$this->layout = 'default';
				break;
			case 'search':
				$this->layout = 'default';
				break;
			default:
				$this->layout = 'panel';
		}
		
	}
	
	public function search(){
		$this->Article->recursive = 0;
		$conditions = array();

		$this->passedArgs['domain_id'] = $conditions['conditions']['Article.domain_id'] = $this->Session->read('Config.domain_id');
		$this->passedArgs['status'] = $conditions['conditions']['Article.status'] = 1;
		
 		$this->Prg->commonProcess();
		$conditions = $this->Article->parseCriteria($this->passedArgs);		

		$this->paginate = array('conditions'=>$conditions,'limit'=>6);

		$articles = $this->paginate();
		
		
		$title_for_layout = __('Wyniki wyszukiwania');
		$keywords = "";
		$description = "";
		$this->set(compact('articles', 'title_for_layout','keywords','description'));
	}
	

/**
 * index method
 *
 * @return void
 */
	
	public function feed() {
		if ($this->RequestHandler->isRss() ) {
			$posts = $this->Article->find('all', array('limit' => 20, 'order' => 'Article.modified DESC', 'conditions' => array('Article.domain_id' => $this->Session->read('Config.domain_id'), 'Article.status' => 1)));
			return $this->set(compact('posts'));
		}	
	}
	
	public function events() {
		$this->autoRender = false;
// 			App::import('Helper', 'text');
// 			$Text = new TextHelper();
		
		//if ($this->RequestHandler->isAjax() ) {
			$article_menu_id = Configure::read('cfg.hompage_article_menu_id');
			$start = date('Y-m-d');
			$end = date('Y-m-d',strtotime("-180 day",strtotime(date('Y-m-d'))));
			
			$posts = $this->Article->find('all', array(
					'order' => 'Article.modified DESC',
					'fields'=>array('Article.name AS title', 'Article.modified AS start', 'url' ),
					'conditions' => 
						array(	'Article.domain_id' => $this->Session->read('Config.domain_id'), 
								'Article.status' => 1,
								'Article.modified <=' => $start, 
								'Article.modified >=' => $end,
								'Article.menuses_id' => $article_menu_id
			)));
			
			$events = array();
			foreach ($posts as $key => $value) {
				$events[$key] = $value['Article'];
// 				$name = $Text->truncate(
// 						$value['Article']['title'],
// 						30,
// 						array(
// 								'ending' => '...',
// 								'exact' => false
// 						)
// 				);
// 				//$events[$key]['title'] = $name;
				$events[$key]['title'] = ">";
			}

			echo json_encode($events);
		//}
	}
	
	
	public function index($menu_id = null) {
		if(is_null($menu_id)){
			$options = array();
			if ($this->request->is('post')){
				if(isset($this->request->data['Article']['domain_id']) && $this->request->data['Article']['domain_id']!= ""){
					$options['conditions']['Article.domain_id'] = $this->request->data['Article']['domain_id'];
					$this->passedArgs['domain_id'] = $this->request->data['Article']['domain_id'];
				}
				if(isset($this->request->data['Article']['status']) && $this->request->data['Article']['status'] !=''){
					$options['conditions']['Article.status'] = $this->request->data['Article']['status'];
					$this->passedArgs['status'] = $this->request->data['Article']['status'];
				}
				$this->paginate = $options;
			}else{
				if(isset($this->passedArgs['domain_id']) && $this->passedArgs['domain_id']!= "") $options['conditions']['Article.domain_id'] = $this->passedArgs['domain_id'];
				if(isset($this->passedArgs['status']) && $this->passedArgs['status'] !='') $options['conditions']['Article.status'] = $this->passedArgs['status'];
						
			}		
		}else{
			$this->loadModel('Menus');
			$this->Menus->recursive = -1;
			$menu = $this->Menus->read(null,$menu_id);
			$options['conditions'] = array('Article.menuses_id' =>$menu_id);
		}
		$this->paginate = $options;
		$this->Article->recursive = 0;
		$articles = $this->paginate();
		$this->loadModel('Domain');
		$domains = $this->Domain->find('list');
		$this->set(compact('articles','domains','menu'));
	}
	
	/**
	 * 
	 * get articles for homepage
	 * @param unknown_type $limit
	 * @param unknown_type $type wartość menu_id pobieran z configurations
	 * @return Ambigous <multitype:, NULL, mixed>
	 */
	public function get($limit, $type = 'cfg.homepage_news_menu_id'){

		$options['joins'] = array(
			array('table' => 'articles_uploads',
		        'alias' => 'ArticlesUpload',
		        'type' => 'left',
		        'conditions' => array('Article.id = ArticlesUpload.article_id'),
		        
				),
			array('table' => 'uploads',
		        'alias' => 'Upload',
		        'type' => 'left',
		        'conditions' => array('ArticlesUpload.upload_id = Upload.id')
				)			
		);
		$options['fields'] = array('Article.name','Article.list_content','Article.slug','Article.modified','Upload.name');
		$options['limit'] = $limit;
		$options['order'] = array('Article.modified DESC');
		$options['conditions'] = array('Article.domain_id' =>  $this->Session->read('Config.domain_id'),'Article.menuses_id' => Configure::read($type));
		return $this->Article->find('all',$options);
	}
	

/**
 * view method
 *
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__d('articles','Invalid article'));
		}
		
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
		// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$data['Article']['domain_id'] = $this->passedArgs['d'];
				$this->request->data = $data;
			}
		}
		$this->loadModel('RatingGroup');
		$doamins = $this->Article->Domain->find('list');
		$users = $this->Article->User->find('list');
		$rating_groups = $this->RatingGroup->find('list');
		$article = $this->Article->read(null, $id);
		
		$this->set(compact('article', 'rating_groups','doamins','users'));
	}
	
	
	public function display($article_id = null) {
		
		$this->review();
	
		$slug = func_get_args();
		$options['conditions'] = array('Article.slug'=>$slug,'Article.domain_id'=>$this->Session->read('Config.domain_id'));
		$article = $this->Article->find('first',$options);
		$article_count = $this->Article->find('count',array('conditions'=>array('Article.menuses_id'=>$article['Article']['menuses_id'])));
		if($path = "/"){
			if(isset($article['Article']['submenu_id']) && !is_null($article['Article']['submenu_id'])){
				$this->loadModel('Submenu');
				$this->Submenu->recursive = -1;
				$this->Submenu->id = $article['Article']['submenu_id'];
				$path = Router::url( "/".$this->Submenu->field('slug'), true );
			}else if(isset($article['Article']['menuses_id']) && !is_null($article['Article']['menuses_id'])){
				$this->loadModel('Menus');
				$this->Menus->recursive = -1;
				$this->Menus->id = $article['Article']['menuses_id'];
				$path = Router::url( "/".$this->Menus->field('slug'), true );	
			}
		}
	
		$path = explode("/", $path);
		$path = $path[count($path)-1];
		$path = array(0=>$path);
		// slugs from menuses
		$links = $this->Menu->getMenu($path);
		$count = count($path);
		if (!$count) {
			$this->redirect('/');
		}
	
	
		if(array_key_exists($path[0], $links) && !empty($path[0])){
	
			$title_for_layout = $article['Article']['name'];
			$article_meta_tags = $article['Article']['metas'];
			$keywords = $article['Article']['keywords'];
			$description = $article['Article']['descriptions'];
			$patchArticle = array('name'=>$article['Article']['name'],'slug'=>$article['Article']['slug']);
				
			$options['joins'] = array(
			array('table' => 'articles_uploads',
											        'alias' => 'ArticlesUpload',
											        'type' => 'inner',
											        'conditions' => array(
											            'Upload.id = ArticlesUpload.upload_id'
			)
			),
			array('table' => 'articles',
											        'alias' => 'Article',
											        'type' => 'inner',
											        'conditions' => array(
											            'ArticlesUpload.article_id = Article.id'
			)
			)
			);
				
			$options['order'] = array(
													    'Upload.type'
			);
				
			$options_rating['joins'] = array(
			array('table' => 'rating_articles',
													        'alias' => 'RatingArticle',
													        'type' => 'inner',
													        'conditions' => array(
													            'Rating.id = RatingArticle.rating_id'
			)
			),
			array('table' => 'articles',
													        'alias' => 'Article',
													        'type' => 'inner',
													        'conditions' => array(
													            'RatingArticle.article_id = Article.id'
			)
			)
			);
				
			$options_rating['order'] = array(
															    'Rating.name'
			);
				
			$options_rating_values['joins'] = array(
			array('table' => 'articles',
													        'alias' => 'Article',
													        'type' => 'inner',
													        'conditions' => array(
													            'RatingValue.article_id = Article.id'
			)
			)
			);
				
				
			$options_comments['joins'] = array(
			array('table' => 'articles_comments',
															        'alias' => 'ArticlesComment',
															        'type' => 'inner',
															        'conditions' => array(
															            'Comment.id = ArticlesComment.comment_id'
			)
			),
			array('table' => 'articles',
															        'alias' => 'Article',
															        'type' => 'inner',
															        'conditions' => array(
															            'ArticlesComment.article_id = Article.id'
			)
			)
			);
				
			$options_posts['joins'] = array(
			array('table' => 'posts_articles',
															        'alias' => 'PostsArticle',
															        'type' => 'inner',
															        'conditions' => array(
															            'Post.id = PostsArticle.post_id'
			)
			),
			array('table' => 'articles',
															        'alias' => 'Article',
															        'type' => 'inner',
															        'conditions' => array(
															            'PostsArticle.article_id = Article.id'
			)
			)
			);
				
			$this->loadModel('Upload');
			$this->Upload->recursive = -1;
			$this->loadModel('Rating');
			$this->Rating->recursive = -1;
			$this->loadModel('RatingValue');
			$this->RatingValue->recursive = -1;
			$this->loadModel('Comment');
			$this->Comment->recursive = -1;
			$this->loadModel('Post');
			$this->Post->recursive = -1;
				
			$options['conditions'] = array( 'Article.id' => $article['Article']['id'] );
			$files_ = $this->Upload->find('all',$options);
				
			$options_rating['conditions'] = array( 'Article.id' => $article['Article']['id'], 'Rating.status' => 1 );
			$ratings = $this->Rating->find('all',$options_rating);
				
			$options_rating_values['conditions'] = array( 'Article.id' => $article['Article']['id']);
			$rating_values = $this->RatingValue->find('all',$options_rating_values);
			$total_ratings = count($rating_values);
			$rating_values = $this->Articles->prepare_rating_values($rating_values,$total_ratings);
				
			$total_calculate = array();
			$total_calculate['count'] = 0;
			$total_calculate['sum'] = 0;
			$i = 1;
			foreach ($rating_values as $rating_id => $rrow) {
				$total_calculate['count'] = $total_calculate['count'] + $rrow['count'];
				$total_calculate['sum'] = $total_calculate['sum'] + $rrow['sum'];
				if($total_calculate['count'] != 0) $total_calculate['serd'] = round( $total_calculate['sum'] / $total_calculate['count']  ,0);
				if($total_calculate['count'] != 0) $total_calculate['proc'] = $i  * 100 /$total_calculate['count'];
					
				$i++;
			}
			$rating_values['total'] = $total_calculate;
				
				
			$options_comments['conditions'] = array( 'Article.id' => $article['Article']['id'] , 'Comment.status' => 1 );
			$comments = $this->Comment->find('all',$options_comments);
	
			$options_posts['conditions'] = array( 'Article.id' => $article['Article']['id'] , 'Post.status' => 1 );
			$posts = $this->Post->find('all',$options_posts);
				
			$gallery = array();
			$download = array();
			if(is_array($files_)){
				foreach ($files_ as $key2 => $file) {
// 					$this->Uploads->upload_file(Configure::read('Config.panel_uploads_folder').$file['Upload']['name'], Configure::read('Config.loacl_uploads_folder'), $file['Upload']['name'], false);
					if(
					$file['Upload']['type'] == 'image/jpeg' ||
					$file['Upload']['type'] == 'image/jpg' ||
					$file['Upload']['type'] == 'image/png' ||
					$file['Upload']['type'] == 'image/gif')
					{
						array_push($gallery, $file);
					}
					if(	$file['Upload']['type'] == 'application/pdf' ||
						$file['Upload']['type'] == 'application/zip'
					 )
					{
						array_push($download, $file);
					}
				}
			}
				
			$article['Gallery'] = $gallery;
			$article['Download'] = $download;
			$article['Rating'] = $ratings;
			$article['RatingValue'] = $rating_values;
			$article['RatingTotal'] = $total_ratings;
			$article['Comment'] = $comments;
			$article['Post'] = $posts;
				
			$this->set(compact('article', 'title_for_layout','keywords','description','article_meta_tags','patchArticle','article_count'));
				
				
// 			$this->render(implode('/', array('view')));
				
	
		}
	
	}
	
	public function review() {

		$slug = func_get_args();
		$options['conditions'] = array('Article.slug'=>$slug,'Article.domain_id'=>$this->Session->read('Config.domain_id'));
		$article = $this->Article->find('first',$options);
			
		if($path = "/"){
			if(isset($article['Article']['submenu_id']) && !is_null($article['Article']['submenu_id'])){
				$this->loadModel('Submenu');
				$this->Submenu->recursive = -1;
				$this->Submenu->id = $article['Article']['submenu_id'];
				$path = Router::url( "/".$this->Submenu->field('slug'), true );
			}else if(isset($article['Article']['menuses_id']) && !is_null($article['Article']['menuses_id'])){
				$this->loadModel('Menus');
				$this->Menus->recursive = -1;
				$this->Menus->id = $article['Article']['menuses_id'];
				$path = Router::url( "/".$this->Menus->field('slug'), true );
			}
		}
	
		if ($this->request->is('post')) {
	
			// 			debug($this->request->data); die;
	
			$this->request->data['Comment']['domain_id'] = $this->Session->read('Config.domain_id');
			$this->request->data['Comment']['ipv4'] = $this->request->clientIp();
	
			if(isset($this->request->data['RatingValue'])){
				$this->loadModel('RatingValue');
				foreach ($this->request->data['RatingValue'] as $rating_id => $value) {
					unset($this->request->data['RatingValue'][$rating_id]);
					array_push($this->request->data['RatingValue'],
					array(
						'article_id'=> (string)$this->request->data['Article']['Article'][0],
						'rating_id'=> (string)$rating_id,
						'rating_value'=> (string)$value ));
				}
				// 				debug($this->request->data); die;
				$this->RatingValue->create();
				if ($this->RatingValue->saveAll($this->request->data['RatingValue'], array('deep' => true))) {
					$this->Session->setFlash(__d('articles','The ratings has been saved'));
	
				} else {
					$this->Session->setFlash(__d('articles','The ratings could not be saved. Please, try again.'));
				}
			}
				
			$this->loadModel('Comment');
			$this->Comment->set($this->request->data);
			if ($this->Comment->validates()) {
				$this->Comment->create();
				if ($this->Comment->save($this->request->data)) {
					$this->Session->setFlash(__d('articles','The comment has been saved'));
	
				} else {
					$this->Session->setFlash(__d('articles','The comment could not be saved. Please, try again.'));
				}
	
// 				$this->redirect($path);
			}
	
	
	
		}
	}

/**
 * add method
 *
 * @return void
 */
	public function add($menu_id = null) {
		if ($this->request->is('post')) {
			$this->request->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
			$this->request->data['Article']['slug'] = strtolower( Inflector::slug($this->request->data['Article']['name'],'-') );
			$this->Article->create();
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__d('articles','The article has been saved'));
				$this->redirect(array('action' => 'index',$menu_id));
			} else {
				$this->Session->setFlash(__d('articles','The article could not be saved. Please, try again.'));
			}
		}
		

		
		
		// dodajemy do domeny
		$this->Article->Domain->id = $this->Session->read('Config.Domain.Domain.id');
		if ($this->Article->Domain->exists()) {
			$data['Article']['domain_id'] = $this->Session->read('Config.Domain.Domain.id');
			$this->request->data = $data;
		}else{
			$this->Session->setFlash(__d('articles','The article could not be saved. Please, select first domain'));
			$this->redirect($this->referer());
		}
	

		$options['joins'] = array(
			array('table' => 'domains_menuses',
				        'alias' => 'DomainsMenus',
				        'type' => 'inner',
				        'conditions' => array(
				            'Menus.id = DomainsMenus.menus_id'
			)
		),
			array('table' => 'domains',
				        'alias' => 'Domain',
				        'type' => 'inner',
				        'conditions' => array(
				            'DomainsMenus.domain_id = Domain.id'
						)
			)
		);
		$options['conditions'] = array(
				    'Domain.id' => $this->Session->read('Config.Domain.Domain.id')
		);
		$options['order'] = array(
						    'Menus.lft'
		);
		
		$this->loadModel('Menus');
		$menuses = $this->Menus->find('threaded',$options);
		$menuses = $this->treeForCombobox($menuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
		
		$ratings_ = $this->Article->Rating->find('all');
		$ratings = array();
		foreach ($ratings_ as $key => $rating) {
			$ratings[$rating['RatingGroup']['name']][$rating['Rating']['id']] = $rating['Rating']['name'] ;
		}
		
		$this->request->data['Article']['menuses_id'] = $menu_id;

		$this->set(compact('menuses','ratings'));

	}
	
	

/**
 * edit method
 *
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__d('articles','Invalid article'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
			$this->request->data['Article']['slug'] = strtolower( Inflector::slug($this->request->data['Article']['name'],'-') );
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__d('articles','The article has been saved'));				
				$this->redirect(array('controller'=>'menuses','action'=>'index'));
			} else {
				$this->Session->setFlash(__d('articles','The article could not be saved. Please, try again.'));
			}
		} else {			
			$this->request->data = $this->Article->read(null, $id);
		}		

// 		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
// 			dodajemy do domeny
// 			$this->Article->Domain->id = $this->passedArgs['d'];
// 			if ($this->Article->Domain->exists()) {
// 				$this->request->data['Article']['domain_id'] = $this->passedArgs['d'];
// 			}
// 		}
				
		$options['joins'] = array(
			array('table' => 'domains_menuses',
				        'alias' => 'DomainsMenus',
				        'type' => 'inner',
				        'conditions' => array(
				            'Menus.id = DomainsMenus.menus_id'
						)
			),
			array('table' => 'domains',
				        'alias' => 'Domain',
				        'type' => 'inner',
				        'conditions' => array(
				            'DomainsMenus.domain_id = Domain.id'
						)
			)
		);
		
		$options['conditions'] = array(
				    'Domain.id' => (isset($this->passedArgs['d'])) ? $this->passedArgs['d'] : $this->request->data['Article']['domain_id']
		);
		
		$this->Article->Menus->recursive = 1;
		$menuses = $this->Article->Menus->find('threaded',$options);	
		
// 		foreach ($menuses as $key1 => $menu) {
// 			if(isset($menu['Submenu']) && is_array($menu['Submenu']) && !empty($menu['Submenu'])){
// 				foreach ($menu['Submenu'] as $key2 => $submenu) {
// 					$menuses[$key1]['children'][count($menuses[$key1]['children'])] = array('Menus'=>array('id'=>$submenu['id'],'parent_id'=>$menu['Menus']['id'],'name'=>$submenu['name']));
// 				}
// 			}
// 		}
		$menuses = $this->treeForCombobox($menuses,'Menus',array('model'=>'Menus','name'=>'name'),false);
// 		$menuses = $this->Article->Menus->find('list');
		
		$options['joins'] = array(
			array('table' => 'menuses_submenus',
			        'alias' => 'MenusesSubmenu',
			        'type' => 'inner',
			        'conditions' => array(
			            'Submenu.id = MenusesSubmenu.submenu_id'
					)
			),
			array('table' => 'menuses',
				'alias' => 'Menus',
				'type' => 'inner',
					'conditions' => array(
						'MenusesSubmenu.menus_id = Menus.id'
					)
			),
			array('table' => 'domains_menuses',
			        'alias' => 'DomainsMenus',
			        'type' => 'inner',
			        'conditions' => array(
			            'Menus.id = DomainsMenus.menus_id'
					)
			),
			array('table' => 'domains',
			        'alias' => 'Domain',
			        'type' => 'inner',
			        'conditions' => array(
			            'DomainsMenus.domain_id = Domain.id'
					)
			),
			
		);
		
		$options['conditions'] = array(
						    'Domain.id' => (isset($this->passedArgs['d'])) ? $this->passedArgs['d'] : $this->request->data['Article']['domain_id']
		);

// 		$this->Article->Submenu->recursive = 1;
// 		$submenuses = $this->Article->Submenu->find('threaded',$options);
// 		$submenus = $this->treeForCombobox($submenuses,'Submenu',array('model'=>'Submenu','name'=>'name'),false);
		$domains = $this->Article->Domain->find('list');
		$ratings_ = $this->Article->Rating->find('all');

		$ratings = array();
		foreach ($ratings_ as $key => $rating) {
			$ratings[$rating['RatingGroup']['name']][$rating['Rating']['id']] = $rating['Rating']['name'] ;
		}
		$this->set(compact('menuses', 'domains','submenus','ratings'));
	}
	
	
	public function edit_rating($id=null){
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__d('articles','Invalid article'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$this->request->data['Article']['user_id'] = $this->Session->read('Auth.User.id');
			$this->request->data['Article']['slug'] = strtolower( Inflector::slug($this->request->data['Article']['name'],'-') );
			if ($this->Article->save($this->request->data)) {
				$this->Session->setFlash(__d('articles','The article has been saved'));
				$this->redirect(array('controller'=>'articles','action' =>'view',$id));				
			} else {
				$this->Session->setFlash(__d('articles','The article could not be saved. Please, try again.'));
			}
		} else {
			$this->request->data = $this->Article->read(null, $id);
			$ratings_ = $this->Article->Rating->find('all');
			$ratings = array();
			foreach ($ratings_ as $key => $rating) {
				$ratings[$rating['RatingGroup']['name']][$rating['Rating']['id']] = $rating['Rating']['name'] ;
			}
			$this->set(compact('ratings'));
		}		
	}	
	
	public function send($id = null) {
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__d('articles','Invalid article'));
		}
		
		$users = $this->Article->User->find('list');
		$domains = $this->Article->Domain->find('list');
		$this->set(compact('users', 'domains'));
		
		if ($this->request->is('post') || $this->request->is('put')) {
// 			debug($this->request->data); die;
			$this->Article->User->id = $this->request->data['Article']['User'];
			$user_email = $this->Article->User->field('email');
			
			$email = new CakeEmail();
			$email->config('gmail');
			$email->log = true;
			
			$email->from(array($this->Session->read('Auth.User.email') => 'SEOsolution'));
			$email->to($user_email);
			$email->subject('Article at : '.$domains[$this->request->data['Article']['domain_id']]);
			$content = __d('articles',"Save at url: ",true).'http://'.$domains[$this->request->data['Article']['domain_id']]."\n\r";
			$content .= __d('articles',"Title: ",true).$this->request->data['Article']['name']."\n\r";
			$content .= Sanitize::html( __d('articles',"Content: ",true).$this->request->data['Article']['content'],array('remove'=>true))."\n\r";
			$content .= __d('articles',"Keywords: ",true).$this->request->data['Article']['keywords']."\n\r";
			$content .= __d('articles',"Description: ",true).$this->request->data['Article']['descriptions']."\n\r";			
			$email->send($content);
			
			$this->Session->setFlash(__d('articles','Article sended'));			
			if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'articles'));
		} else {
			$this->request->data = $this->Article->read(null, $id);
		}
	
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$this->request->data['Article']['domain_id'] = $this->passedArgs['d'];
			}
		}
	

		
	}

/**
 * delete method
 *
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Article->id = $id;
		if (!$this->Article->exists()) {
			throw new NotFoundException(__d('articles','Invalid article'));
		}
		if ($this->Article->delete()) {
			$this->Session->setFlash(__d('articles','Article deleted'));
			$this->redirect(array('controller'=>'menuses','action'=>'index'));
		}
		$this->Session->setFlash(__d('articles','Article was not deleted'));
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])) $this->redirect(array('controller'=>'domains','action' =>'view',$this->passedArgs['d'],'d'=>'articles'));
		$this->redirect($this->referer());
	}
	
	
/**
 *  add file
 */	
	public function add_file() {		
			
		if($this->FileUpload->success){
			if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])) $this->redirect(array('controller'=>'articles','action' =>'view',$this->passedArgs['a']));				
		}else{
			$this->Session->setFlash($this->FileUpload->showErrors());
		}

		$data = array();
		if(isset($this->passedArgs['d']) && !empty($this->passedArgs['d'])){
			// dodajemy do domeny
			$this->Article->Domain->id = $this->passedArgs['d'];
			if ($this->Article->Domain->exists()) {
				$data['Upload']['domain_id'] = $this->passedArgs['d'];
			}else{
				$this->Session->setFlash(__d('articles','The article could not be saved. Please, select first domain'));
				$this->redirect($this->referer());
			}
			
			if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])){
				// dodajemy do domeny
				$this->Article->id = $this->passedArgs['a'];
				if ($this->Article->exists()) {
					$data['Article']['id'] = $this->passedArgs['a'];
					$this->request->data = $data;
				}
			}
		}	

	}
	
/**
 * delete file
 */	
	public function delete_file($id = null){
		$this->autoRender = false;
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}

		$this->Article->Upload->id = $id;
		if (!$this->Article->Upload->exists()) {
			throw new NotFoundException(__d('articles','Invalid file'));
		}
		
		if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])){
			// dodajemy do domeny
			$this->Article->id = $this->passedArgs['a'];
			if ($this->Article->exists()) {
				$data['Article']['id'] = $this->passedArgs['a'];
				$this->request->data = $data;
			}
		}
		
		$upload = $this->Article->Upload->findById($id);		
		
		$this->FileUpload->removeFile($upload['Upload']['name']);		
		if($this->Article->Upload->delete($id)){
			$this->Session->setFlash('Upload deleted');
			if(isset($this->passedArgs['a']) && !empty($this->passedArgs['a'])) $this->redirect(array('controller'=>'articles','action' =>'view',$this->passedArgs['a']));
			$this->redirect(array('action'=>'index'));
		}
		$this->redirect(array('action'=>'index'));
	}
	
}
